<script setup>
import PageContainer from "@/components/PageContainer.vue";
import { useUserStore } from "@/stores";
import { Plus, Upload } from "@element-plus/icons-vue"
import { ref } from "vue";
import { userUpdateAvatarService } from "@/api/user";
import { ElMessage } from "element-plus";
// 基于store的数据，初始化imageUrl的初始值
const userStore = useUserStore()
const imageUrl = ref(userStore.user.userPic)
// 绑定upload输入框
const uploadRef = ref()
// 选择文件
const onSelectFile = async (uploadFile) => {
  await new Promise((resolve) => {
    // imageUrl.value = URL.createObjectURL(uploadFile.raw)
    const reader = new FileReader()
    reader.readAsDataURL(uploadFile.raw)
    reader.onload = (e) => {
      imageUrl.value = e.target.result
      resolve()
    }
  })
}
const onUpdateAvatar = async () => {
  if (imageUrl.value === userStore.user.userPic) return
  await userUpdateAvatarService(imageUrl.value)
  userStore.getUser()
  ElMessage.success("头像更新成功")
}
</script>

<template>
  <PageContainer title="更换头像">
    <el-upload class="avatar-uploader" :show-file-list="false" :auto-upload="false" ref="uploadRef"
      :on-change="onSelectFile">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon">
        <Plus />
      </el-icon>
    </el-upload>
    <br>
    <el-button type="primary" :icon="Plus" @click="uploadRef.$el.querySelector('input').click()">选择图片</el-button>
    <el-button type="success" :icon="Upload" @click="onUpdateAvatar">上传图片</el-button>
  </PageContainer>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
